<template>
  <!-- 接受数据 没有数据 如何清空原来的数据 v-if="img"-->
  <div class="image-canvas">
    <canvas ref="newCanvas" class="canvas-center" v-if="img"></canvas>
    <el-empty v-else description="暂无数据" class="ElEmpty" />
  </div>
</template>

<script setup lang='ts'>
import { reactive, ref, onMounted, onDeactivated } from 'vue'
const props = defineProps({
  img: {
    type: String,
    default: ''
  },
  imgObj: {
    type: Object as any,
    default: () => { }
  },
  recordList: {
    type: Array,
    default: () => []
  },
  type: {
    type: String,
    default: 'R'
  }
})
onMounted(() => {
})
const emit = defineEmits(['inputPos'])
// 来一个数据
const newCanvas = ref()
let canvasData = reactive({
  canvas: null as any,
  pointerDownLocation: {} as any,
  dragging: false,
  ctx: null as any,
  imgData: null as any,
  t_PointerMove: false,
  rubberBandRect: {} as any,
  rectList: [] as any,
  historyList: [] as any,
  isClickBack: false,
  initImg: null as any,
  imageObj: null as any,
  src: ''

})
// 如果是切换页码 全部清空数据 重新加载...
const clearCanvasDate = () => {
  canvasData = {
    canvas: null as any,
    src: '',
    pointerDownLocation: {} as any,
    dragging: false,
    ctx: null as any,
    imgData: null as any,
    t_PointerMove: false,
    rubberBandRect: {} as any,
    rectList: [] as any,
    historyList: [] as any,
    isClickBack: false,
    initImg: null as any,
    imageObj: null as any,
  }
}
// 来吧 怎么操作这个东西
// 图片加载
const initImage = () => {
  canvasData.canvas = newCanvas.value
  canvasData.ctx = canvasData.canvas.getContext('2d')
  canvasData.ctx.save()
  canvasData.ctx.scale(0.5, 0.5)
  const image = new Image()
  image.setAttribute('crossOrigin', 'anonymous')
  image.src = props.img
  image.addEventListener('load', () => {
    // 图片加载完，再draw 和 toDataURL
    console.log(image.width, image.height, '650', 794 / image.width) // 2481 3508
    const canvasHeight = Math.ceil(image.height * (794 / image.width))
    if (image.complete) {
      // A4 横向 width 794  height 1123 纵向 width 1123 height 794
      canvasData.canvas.width = 794
      canvasData.canvas.height = canvasHeight
      canvasData.imageObj = image
      canvasData.ctx.drawImage(image, 0, 0, 794, canvasHeight)
      canvasData.ctx.globalCompositeOperation = 'R' // 干嘛的
      canvasData.canvas.addEventListener('pointerdown', onPointerDown)
      canvasData.canvas.addEventListener('pointermove', onPointerMove)
      canvasData.canvas.addEventListener('pointerup', onPointerUp)
      const imgData = canvasData.canvas.toDataURL()
      canvasData.initImg = canvasData.canvas.toDataURL()
      canvasData.historyList.push({ img: imgData, width: canvasData.canvas.width, height: canvasData.canvas.height, top: 0, left: 0 })
      if (props.imgObj.commentsDTOs) {
        addHistoryList(props.imgObj.commentsDTOs)
      }
    }
  })
}
// 添加历史标注
const addHistoryList = (list) => {
  if (!(Array.isArray(list) && list.length > 0)) {
    return
  }
  console.log(list.length, list, 'length')
  for (let i = 0; i < list.length; i++) {
    // console.log(list[i], '噢噢噢噢')
    // // console.log(list[i], '我iii')
    const e = list[i]
    const [item] = e
    if (!item) continue
    const loca = {
      left: Number(item.distLeft),
      top: Number(item.distTop),
      width: Number(item.width),
      height: Number(item.height)
    }
    // 这个地方就是 把react 画出来的具体操作
    addDrawShape(loca) // 矩形
    addDrawTxt(loca) // 编号
    // this.addDrawCloseTxt(loca) // 关闭
    recordHisy(loca) // 历史记录
  }
}
const addDrawTxt = (location) => {
  const ctx = canvasData.ctx
  ctx.save()
  ctx.fillStyle = 'red'
  const index = canvasData.historyList.length
  ctx.fillText(index, location.left, location.top - 6)
  ctx.save()
}
const addDrawShape = (location) => {
  const ctx = canvasData.ctx
  ctx.save()
  ctx.beginPath()
  ctx.strokeStyle = 'red'
  ctx.rect(location.left, location.top, location.width, location.height)
  ctx.stroke()
  ctx.closePath()
  ctx.restore()
}
// 第一步 鼠标按下
const onPointerDown = (e) => {
  console.log(e, 'pppp')
  var location = unifyCoordinates(e.clientX, e.clientY)
  canvasData.pointerDownLocation.x = location.x
  canvasData.pointerDownLocation.y = location.y
  canvasData.dragging = true
  saveData()
}
const saveData = () => {
  const ctx = canvasData.ctx
  canvasData.imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height)
  canvasData.ctx.putImageData(canvasData.imgData, 0, 0)
}
// 相对于画布元素的坐标转换为相对于画布大小的坐标
const unifyCoordinates = (x, y) => {
  const canvas = canvasData.canvas
  const rect = canvas.getBoundingClientRect()
  return {
    x: Math.floor((x - rect.left) * (canvas.width / rect.width)) + 0.5,
    y: Math.floor((y - rect.top) * (canvas.height / rect.height)) + 0.5
  }
}
// 鼠标移动 ----
const onPointerMove = (e) => {
  if (props.type !== 'R') {
    return
  }
  if (canvasData.dragging) {
    canvasData.t_PointerMove = true
    const location = unifyCoordinates(e.clientX, e.clientY)
    restoreData()
    makeRect(location)
    drawShape(location)
  }
}
// 当前img放入canvas
const restoreData = () => {
  canvasData.ctx.putImageData(canvasData.imgData, 0, 0)
}
// 标记矩形绘制数据
const makeRect = (location) => {
  if (canvasData.pointerDownLocation.x < location.x) {
    canvasData.rubberBandRect.left = canvasData.pointerDownLocation.x
  } else {
    canvasData.rubberBandRect.left = location.x
  }

  if (canvasData.pointerDownLocation.y < location.y) {
    canvasData.rubberBandRect.top = canvasData.pointerDownLocation.y
  } else {
    canvasData.rubberBandRect.top = location.y
  }
  canvasData.rubberBandRect.width = Math.abs(canvasData.pointerDownLocation.x - location.x)
  canvasData.rubberBandRect.height = Math.abs(canvasData.pointerDownLocation.y - location.y)
}
// 矩形绘制
const drawShape = (location) => {
  const ctx = canvasData.ctx
  ctx.save()
  ctx.beginPath()
  ctx.strokeStyle = 'red'
  ctx.rect(canvasData.rubberBandRect.left, canvasData.rubberBandRect.top, canvasData.rubberBandRect.width, canvasData.rubberBandRect.height)
  canvasData.rectList.push(canvasData.rubberBandRect)
  const temp = {} as any
  const result = [] as any
  canvasData.rectList.map((item: any, index) => {
    if (!temp[item.left && item.width]) {
      result.push(item)
      temp[item.left && item.width] = true
    }
  })
  ctx.stroke()
  ctx.closePath()
  ctx.restore()
}
// 鼠标抬起
const onPointerUp = (e) => {
  if (props.type !== 'R') {
    return
  }
  if (canvasData.dragging) {
    var location = unifyCoordinates(e.clientX, e.clientY)

    canvasData.dragging = false
    restoreData()
    makeRect(location)
    drawShape(location)
    if (canvasData.rubberBandRect.width && canvasData.rubberBandRect.height) {
      // 数据判断 一对多得判断
  console.log(canvasData.historyList.length, '数据判断 一对多得判断')

      emit('inputPos', canvasData.rubberBandRect, canvasData.historyList.length)
      if (canvasData.t_PointerMove) {
        drawTxt(location)
        recordHisy(canvasData.rubberBandRect)
        canvasData.t_PointerMove = false
      }
    }
  }
}
// 矩形编号
const drawTxt = (location) => {
  console.log(canvasData.historyList.length, '矩形编号')
  const ctx = canvasData.ctx
  ctx.save()
  ctx.fillStyle = 'red'
  const index = canvasData.historyList.length
  ctx.fillText(index, canvasData.rubberBandRect.left, canvasData.rubberBandRect.top - 6)
  ctx.save()
}
// 历史记录保存
const recordHisy = (loca) => {
  // console.log(loca, 'llloc')
  canvasData.isClickBack = true
  const imgData = canvasData.canvas.toDataURL()
  // 就是history 多了一个数据 怎么处理的 请问删除
  // console.log(canvasData.historyList)
  canvasData.historyList.push({ img: imgData, width: loca.width, height: loca.height, top: loca.top, left: loca.left })
}
// 组件失活
onDeactivated(() => {
  canvasData.canvas.removeEventListener('pointerdown', onPointerDown)
  canvasData.canvas.removeEventListener('pointermove', onPointerMove)
  canvasData.canvas.removeEventListener('pointerup', onPointerUp)
})
const newDraw = (commentsDTOs) => {

  // this.historylist 有问题 他的长度怎么处理的 有没有用重置
  canvasData.historyList = [canvasData.historyList[0]]
  const imgdata = canvasData.historyList[0].img
  canvasData.src = imgdata
  if (imgdata) {
    const canvasPic = new Image()
    canvasPic.src = imgdata
    canvasPic.addEventListener('load', () => {
      canvasData.ctx.clearRect(0, 0, canvasData.canvas.width, canvasData.canvas.height)
      canvasData.ctx.drawImage(canvasPic, 0, 0)
      if (commentsDTOs.length) {
        addHistoryList(commentsDTOs)
      }
    })
  }
}
defineExpose({
  initImage, clearCanvasDate, newDraw
})
</script>
<style scoped lang='scss'>
.image-canvas {
  height: 100%;
  width: 100%;
  // background-color: rgba(100, 0, 100, 0.2);

  .canvas-center {
    // margin: 0 auto;
    margin-left: 10px;
  }

  .ElEmpty {
    width: 400px;
    margin: 0 auto;
    margin-top: 200px;
  }
}
</style>